var http = require('http')
var fs = require('fs')
var template = require('art-template')
var url = require('url')

var comments = [{
        name: '张三',
        message: '可以给我你的微信吗',
        dateTime: '2020-02-21'
    },
    {
        name: '张三1',
        message: '可以给我你的微信吗',
        dateTime: '2020-02-21'
    }, {
        name: '张三2',
        message: '可以给我你的微信吗',
        dateTime: '2020-02-21'
    }
]

http
    .createServer(function(req, res) {

        var parseObj = url.parse(req.url, true)

        var pathname = parseObj.pathname

        if (pathname === '/') {
            fs.readFile('./views/index.html', function(err, data) {
                if (err) {
                    return res.end('404 Not Found')
                }
                var htmlstr = template.render(data.toString(), {
                    comments: comments
                })
                res.end(htmlstr)
            })
        } else if (pathname === '/post') {
            fs.readFile('./views/post.html', function(err, data) {
                if (err) {
                    return res.end('404 Not Found')
                }
                res.end(data)
            })
        } else if (pathname === '/pinglun') {
            //获取表单数据parseObj.query
            var comment = parseObj.query

            //生成当前日期，存储到数组中
            comment.dateTime = '2020-08-06'

            comments.unshift(comment)

            //跳转到首页，状态码设置为302意为临时重定向，然后在响应头中的lacation中设置路径
            res.statusCode = 302 //写入状态码
            res.setHeader('Location', '/') //路径
            res.end()
        } else if (pathname.indexOf('/public/') === 0) {
            //.是使得变为./
            fs.readFile('.' + pathname, function(err, data) {
                if (err) {
                    return res.end('404 Not Found')
                }
                res.end(data)
            })
        } else { //如果是其他路径
            fs.readFile('./views/404.html', function(err, data) {
                if (err) {
                    return res.end('404 Not Found')
                }
                res.end(data)
            })
        }
    })
    .listen(3000, function() {
        console.log('server is runing...')
    })